package com.otaku.admin.util;

import com.alibaba.fastjson.JSON;
import com.otaku.admin.dao.entity.SelfUserDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: zzx
 * @date: 2018/10/16 9:06
 * @description: jwt生成token
 */
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtTokenUtil {

    /**
     * 生成token
     *
     * @param userDTO
     * @return
     */

    public static String generateToken(SelfUserDetails userDTO) {
        Long time = NumericTypeConstant.ACCESS_TOKEN_TIME_OUT;
        Map<String, Object> map = new HashMap<>(1);
        map.put("user", userDTO);
        return Jwts.builder()
                .setClaims(map)
                .setSubject(userDTO.getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + time * 1000L))
                .signWith(SignatureAlgorithm.HS512, StringTypeConstant.SECRET_TOKEN)
                .compact();
    }

    /**
     * 生成token
     *
     * @param userDTO 用户信息
     * @param time    有效期 秒
     * @return
     */
    public static String generateToken(SelfUserDetails userDTO, Long time) {
        Map<String, Object> map = new HashMap<>(1);
//        map.put("user",userDTO); //不存入全部用户信息，防止泄露
        map.put("user", userDTO.getUsername());
        return Jwts.builder()
                .setClaims(map)
                .setSubject(userDTO.getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .signWith(SignatureAlgorithm.HS512, StringTypeConstant.SECRET_TOKEN)
                .compact();
    }

    /**
     * 获取用户名
     *
     * @param token
     * @return
     */
    public static String parseTokenStr(String token) {
        return parseToken(token).getSubject();
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(StringTypeConstant.SECRET_TOKEN)
                .parseClaimsJws(token)
                .getBody();
    }

//    /**
//     * 获取userDTO
//     *
//     * @param token
//     * @return
//     */
//    public SelfUserDetails getUser(String token) {
//        Claims claims = parseToken(token);
//        Map<String, String> map = claims.get("user", Map.class);
//        SelfUserDetails userDTO = JSON.parseObject(JSON.toJSONString(map), SelfUserDetails.class);
//        return userDTO;
//    }

    // 是否已过期
    public static boolean isExpiration(String token) {
        return parseToken(token).getExpiration().before(new Date());
    }


}
